/**
 * openfire_src
 */
package com.kingray.openfire.plugin.dao.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

import org.jivesoftware.util.cache.Cache;
import org.jivesoftware.util.cache.CacheFactory;

import com.kingray.openfire.plugin.dao.EmotionDAO;
import com.kingray.openfire.plugin.vo.Emotion;

/**
 * 实现了缓存的数据库操作类
 * @author 瑛琪 <a href="http://xiongyingqi.com">xiongyingqi.com</a>
 * @version 2013-9-5 下午5:20:25
 */
public class EmotionDAOCachedImpl extends EmotionDAOImpl implements EmotionDAO{
	private static Cache<String, Emotion> cache;
	
	private void addToCache(Emotion emotion){
		if(cache == null){
			cache = CacheFactory.createCache("KingrayEmotion");
		}
		cache.put(emotion.getEmotionId(), emotion);
	}
	
	private Emotion getCache(String id){
		return cache.get(id);
	}
	
	private Collection<Emotion> getAll(){
		Collection<Emotion> emotions = new ArrayList<Emotion>();
		Set<Entry<String, Emotion>> entries = cache.entrySet();
		for (Iterator iterator = entries.iterator(); iterator.hasNext();) {
			Entry<Integer, Emotion> entry = (Entry<Integer, Emotion>) iterator.next();
			Emotion emotion = entry.getValue();
			emotions.add(emotion);
		}
		return emotions;
	}
	
	
	/**
	 * <br>2013-9-5 下午5:21:16
	 * @see com.kingray.openfire.plugin.dao.EmotionDAO#getAllEmotions()
	 */
	@Override
	public Collection<Emotion> getAllEmotions() {
		return getAll();
	}

	/**
	 * <br>2013-9-5 下午5:21:16
	 * @see com.kingray.openfire.plugin.dao.EmotionDAO#getEmotion(java.lang.String)
	 */
	@Override
	public Emotion getEmotion(String emotionId) {
		return getCache(emotionId);
	}

	/**
	 * <br>2013-9-5 下午5:21:16
	 * @see com.kingray.openfire.plugin.dao.EmotionDAO#addEmotion(com.kingray.openfire.plugin.vo.Emotion)
	 */
	@Override
	public Emotion addEmotion(Emotion emotion) {
		emotion = super.addEmotion(emotion);
		addToCache(emotion);
		return emotion;
	}
	
}
